package binarytree;

import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/20 18:10
 * https://leetcode-cn.com/problems/same-tree/
 * 给你两棵二叉树的根节点 p 和 q ，编写一个函数来检验这两棵树是否相同。
 * 如果两个树在结构上相同，并且节点具有相同的值，则认为它们是相同的。
 */
public class IsSameTree {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 递归方法
     * @param p
     * @param q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q != null) {
            return false;
        } else if (p != null && q == null) {
            return false;
        } else if (p == null && q == null) {
            return true;
        } else if (p.val != q.val) {
            return false;
        } else {
            //此时p.val == q.val
            return isSameTree(p.left, q.right) && isSameTree(p.right, q.left);
        }
    }

    /**
     * 类似层次遍历重点判断每个节点的左右孩子是否相等
     * @param p
     * @param q
     * @return
     */
    public boolean isSameTree1(TreeNode p, TreeNode q) {
        Stack<TreeNode> stack = new Stack<>();
        stack.push(p);
        stack.push(q);
        while (!stack.isEmpty()) {
            TreeNode left= stack.pop();
            TreeNode right = stack.pop();
            //当节点为空直接跳过，此时与递归法不同
            if (left == null && right == null) {
                continue;
            }
            if (left == null && right != null) {
                return false;
            } else if (left != null && right == null) {
                return false;
            } else if (left.val != right.val) {
                return false;
            } else {
                stack.push(left.left);
                stack.push(right.left);
                stack.push(left.right);
                stack.push(right.right);
            }
        }
        return true;
    }


    public static void main(String[] args) {

    }
}
